﻿using FinalPointSet.Model.Constant;
using FinalPointSet.Model.Constant.Message;
using FinalPointSet.Model.Constants;
using FinalPointSet.Model.Manager;
using FinalPointSet.Model.Util;
using HandyControl.Controls;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media.Animation;
using Menu = FinalPointSet.Model.Model.Menu;
using PG = System.Windows.Controls;
using Window = System.Windows.Window;
namespace FinalPointSet.View
{
    /// <summary>
    /// MainView.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : Window
    {
        /// <summary>
        /// 是否展开
        /// </summary>
        public bool isExpand = true;
        /// <summary>
        /// 上一次页面路径
        /// </summary>
        private string lastPagePath = PageUtil.FieldMappingPage;
        /// <summary>
        /// 当前页面路径
        /// </summary>
        private string currentPagePath = PageUtil.FieldMappingPage;
        /// <summary>
        /// 监听ID
        /// </summary>
        private readonly int growMsgListenID;
        /// <summary>
        /// 当期屏幕名称
        /// </summary>
        private string currentScreenName = string.Empty;
        /// <summary>
        /// 是否拖拽窗体
        /// </summary>
        private bool isDrag = false;
        public MainView()
        {
            InitializeComponent();
            PageUtil.Instance.Init(PageFrame);
            //初始化导航栏展开状态
            SetExpandState(Settings.Default.IsExpand);

            //页面路径
            SecondPathLabel.Visibility = Visibility.Hidden;
            SymbalLabel.Visibility = Visibility.Hidden;
            BackToLastPathButton.Visibility = Visibility.Hidden;
            PageUtil.Instance.OnPageChange += (page) =>
            {
                FirstPathLabel.Text = page.FirstPath;
                lastPagePath = page.FirstPath;
                //判断当前页面是否有二级页面
                if (!string.IsNullOrEmpty(page.SecondPath))
                {
                    currentPagePath = page.SecondPath;
                    FirstPathLabel.ToolTip = StringResourceManager.Instance.Get("BackToPrevious"); ;
                    SecondPathLabel.Text = page.SecondPath;
                    SecondPathLabel.Visibility = Visibility.Visible;
                    SymbalLabel.Visibility = Visibility.Visible;
                    BackToLastPathButton.Visibility = Visibility.Visible;
                }
                else
                {
                    currentPagePath = page.FirstPath;
                    FirstPathLabel.ToolTip = page.FirstPath;
                    SecondPathLabel.Visibility = Visibility.Hidden;
                    SymbalLabel.Visibility = Visibility.Hidden;
                    BackToLastPathButton.Visibility = Visibility.Hidden;
                }
            };

            //弹出信息处理
            growMsgListenID = MessageManager.Listening(MsgType.GrowMsg, (msgArg) =>
            {
                if (msgArg is not GrowMsgArg growMsgArg)
                    return;
                if (!WindowType.MainView.Equals(growMsgArg.WindowType))
                    return;

                switch (growMsgArg.Key)
                {
                    case GrowlMsgType.Info:
                        Growl.Info(growMsgArg.Value);
                        break;
                    case GrowlMsgType.Success:
                        Growl.Success(growMsgArg.Value);
                        break;
                    case GrowlMsgType.Warning:
                        Growl.Warning(growMsgArg.Value);
                        break;
                    case GrowlMsgType.Error:
                        Growl.Error(growMsgArg.Value);
                        break;
                    case GrowlMsgType.Fatal:
                        Growl.Fatal(growMsgArg.Value);
                        break;
                    case GrowlMsgType.Clear:
                        Growl.Clear(growMsgArg.Value);
                        break;
                    default:
                        Growl.Info(growMsgArg.Value);
                        break;
                }

            });
        }

        private void NavMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Debug.Print("ListBox_SelectionChanged");

            if (NavMenu.SelectedItems[0] is not Menu menu)
            {
                Debug.Print("ListBox_SelectionChanged选择为空");
                return;
            }

            if (PageFrame is null) return;
            PageUtil.Instance.Navigate(PageFrame, menu.Page);

        }

        /// <summary>
        /// 设置侧边导航栏展开\收起
        /// </summary>
        /// <param name="isExpand"></param>
        private void SetExpandState(bool isExpand)
        {
            this.isExpand = isExpand;
            if (isExpand)
            {
                ExpandButton.Text = "\uef99";
                NavBar.Width = Config.MainWindowNavBarExpandWidth;
            }
            else
            {
                ExpandButton.Text = "\uef9a";
                NavBar.Width = Config.MainWindowNavBarUnExpandWidth;
            }
        }

        //展开按钮事件
        private void TextBlock_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Debug.Print("MainView.TextBlock_MouseDown()");

            if (isExpand)
            {
                isExpand = false;
                ExpandButton.Text = "\uef9a";
                DoubleAnimation widthAnimation = new()
                {
                    From = Config.MainWindowNavBarExpandWidth,
                    To = Config.MainWindowNavBarUnExpandWidth,
                    Duration = new Duration(TimeSpan.FromSeconds(0.3)),
                    EasingFunction = new QuadraticEase
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                };
                NavBar.BeginAnimation(WidthProperty, widthAnimation);
            }
            else
            {
                isExpand = true;
                NavBar.Width = Config.MainWindowNavBarExpandWidth;
                ExpandButton.Text = "\uef99";
                DoubleAnimation widthAnimation = new()
                {
                    From = Config.MainWindowNavBarUnExpandWidth,
                    To = Config.MainWindowNavBarExpandWidth,
                    Duration = new Duration(TimeSpan.FromSeconds(0.3)),
                    EasingFunction = new QuadraticEase
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                };
                NavBar.BeginAnimation(WidthProperty, widthAnimation);
            }
            Settings.Default.IsExpand = isExpand;
            Settings.Default.Save();
        }

        private void WindowBorder_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                isDrag = true;
                DragMove();
            }
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            WindowUtil.Instance.Remove(GetType());
            MessageManager.CancelListening(MsgType.GrowMsg, growMsgListenID);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            WindowUtil.Instance.Add(this, GetType());
            //唤醒窗体
            Activate();
            currentScreenName = ScreenUtil.GetScreenFromWindowPosition(this).DeviceName;
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Debug.Print($"Window_SizeChanged, WindowState={WindowState}");
            if (WindowState == WindowState.Maximized)
            {
                WindowBorder.Margin = new Thickness(0);
                WindowBorder.CornerRadius = new CornerRadius(0);
            }
            else if (WindowState == WindowState.Normal)
            {
                WindowBorder.Margin = new Thickness(1);
                WindowBorder.CornerRadius = new CornerRadius(20);
            }
        }

        private void BackToLastPathButton_Click(object sender, RoutedEventArgs e)
        {
            Debug.Print("MainView.BackToLastPathButton_Click()");
            PageUtil.Instance.Navigate(lastPagePath);
        }

        private void FirstPathLabel_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Debug.Print("MainView.BackToLastPathButton_Click()");
            if (!currentPagePath.Equals(lastPagePath))
            {
                Debug.Print($"MainView.BackToLastPathButton_Click(), 返回上一级页面:{lastPagePath}");
                PageUtil.Instance.Navigate(lastPagePath);
            }
        }

        private void PageFrame_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (PageFrame.Content is PG.Page currentPage)
            {
                // 创建一个淡入动画
                DoubleAnimation fadeIn = new()
                {
                    From = 0,
                    To = 1,
                    Duration = new Duration(TimeSpan.FromSeconds(0.5)),
                    AutoReverse = false,
                    EasingFunction = new QuadraticEase
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                };

                // 将动画应用到Page的Opacity属性
                currentPage.BeginAnimation(OpacityProperty, fadeIn);
            }
        }

        private void PageFrame_ContentRendered(object sender, EventArgs e)
        {
            // 将新页面的初始Opacity设置为0，以便动画可以从0开始
            if (PageFrame.Content is PG.Page currentPage)
            {
                currentPage.Opacity = 0;
            }
        }


        private void Window_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (isDrag)
            {
                isDrag = false;
                //更新分辨率
                Screen screen = ScreenUtil.GetScreenFromWindowPosition(this);
                if (!screen.DeviceName.Equals(currentScreenName))
                {
                    currentScreenName = screen.DeviceName;
                    Debug.Print($"Window_MouseUp, 窗体所处屏幕变化, 新的窗体: {currentScreenName}");
                    WindowUtil.Instance.UpdateWindowDPI(typeof(MainView), screen);
                }
            }
        }

        private void FirstPathLabel_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (SecondPathLabel.Visibility == Visibility.Visible)
            {
                FirstPathLabel.Cursor = System.Windows.Input.Cursors.Hand;
            }
        }

        private void FirstPathLabel_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            FirstPathLabel.Cursor = System.Windows.Input.Cursors.Arrow;
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            Growl.SetGrowlParent(GrowlPanel, true);
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            Growl.SetGrowlParent(GrowlPanel, false);
        }
    }
}
